# This code is hosted on http://code.google.com/p/lenthorp/
# Freely available for use in applications, but should NOT be modified
# Email all comments to lenthorpresearch@gmail.com

import PricingEngineMod
from PricingEngineMod import *
reload(PricingEngineMod)

from math import exp, log, sqrt, pow
from scipy.stats import norm

# modelParams:
# otherParams: vol, strike, tenor, rate, initial, div
class BlackScholesAnalytical(PricingEngine):

    def getPrice(self):
        if (self.currentStatus > 0):
            op = self.otherParams.p
            mp = self.modelParams.p
            d1 = (log(op['initial'] / op['strike']) + (op['rate'] + 0.5 * pow(op['vol'],2)) * op['tenor']) / (op['vol'] * sqrt(op['tenor']))
            d2 = d1 - (op['vol'] * sqrt(op['tenor']))
            if (mp['type'] == 'call'):
                val = (op['initial'] * exp(-op['div'] * op['tenor']) * norm.cdf(d1)) - (op['strike'] * exp(-op['rate'] * op['tenor']) * norm.cdf(d2))
            else:
                val = (op['strike'] * exp(-op['rate'] * op['tenor']) * norm.cdf(-d2)) - (op['initial'] * exp(-op['div'] * op['tenor']) * norm.cdf(-d1))
            return val